<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 包邮卡 统计
 * Class postal_card
 */
class PostalCard extends MY_Controller {
    /**
     * @var ConsumerPostalCardModel
     */
    public $mPostalCard = null;

	public function __construct(){
		parent::__construct();
		$this->loadModel('ConsumerPostalCardModel', 'mPostalCard', 'consumer');
	}
	
	/**
	 * 首页
	 */
	public function index(){
        // 最近1个月
        $startTime = strtotime("-1 month");

        $data = array(
            'startTime' => dateFormat($startTime),
            'endTime' => dateFormat(time()),
        );
		$this->view('statistics/postalCard', $data, 'datatable,date_range_picker');
	}

    /**
     * 获取数据
     */
    public function getList(){
        $data = $this->mPostalCard->getStatisticsLog();
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['name'];
            $data['aaData'][$k][] = $v['money'];
            $data['aaData'][$k][] = $v['send_number'];
            $data['aaData'][$k][] = $v['used'];
            $data['aaData'][$k][] = $v['not_used'];
            $data['aaData'][$k][] = $v['use_end'];
            $data['aaData'][$k][] = isset($v['used_money']) ? $v['used_money'] : 0;
            $data['aaData'][$k][] = $v['total_money'];
            $data['aaData'][$k][] = dateFormat($v['use_end_time']);
            $data['aaData'][$k][] = dateFormat($v['addtime']);
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 导出
     * @author defcu
     */
    public function export(){
        $timeGap = trim(get('timegap'));
        $timeGapArr = explode(' - ', $timeGap);
        $filename = '包邮卡统计'.$timeGapArr[0].'-'.$timeGapArr[1].'.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('名称,发放金额,发放数量,使用数量,未使用数量,失效数量,使用总金额,发放总金额,截至时间,发放时间','gb2312','utf-8')."\n";
        $pageNumber = 500;
        $page = 1;
        while(true){
            $list = $this->mPostalCard->getStatisticsLog($page, $pageNumber);
            if(empty($list)){
                break;
            }
            $page ++;
            foreach($list as $v){
                $used_money = isset($v['used_money']) ? $v['used_money'] : 0;
                echo mb_convert_encoding($v['name'].','.$v['money'].','.$v['send_number'].','.$v['used'].','.$v['not_used'].','.$v['use_end'].','.$used_money.','. $v['total_money'].','. dateFormat($v['use_end_time']).','. dateFormat($v['addtime']), 'gb2312','utf-8')."\n";
            }
        }
    }
}
